
package com.example.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.zxing.WriterException;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.widget.ImageView;

public class Utils {
	public static String path = null;

	public static final String DAY_NIGHT_MODE = "daynightmode";
	public static final String DEVIATION = "deviationrecalculation";
	public static final String JAM = "jamrecalculation";
	public static final String TRAFFIC = "trafficbroadcast";
	public static final String CAMERA = "camerabroadcast";
	public static final String SCREEN = "screenon";
	public static final String THEME = "theme";
	public static final String ISEMULATOR = "isemulator";

	public static final String ACTIVITYINDEX = "activityindex";

	public static final int SIMPLEHUDNAVIE = 0;
	public static final int EMULATORNAVI = 1;
	public static final int SIMPLEGPSNAVI = 2;
	public static final int SIMPLEROUTENAVI = 3;

	public static final boolean DAY_MODE = false;
	public static final boolean NIGHT_MODE = true;
	public static final boolean YES_MODE = true;
	public static final boolean NO_MODE = false;
	public static final boolean OPEN_MODE = true;
	public static final boolean CLOSE_MODE = false;

	private static float defaultDensity = 1.5f;// 高分辨率的手机density普遍接近1.5

	/**
	 * 获取app的存储目�?
	 * <p>
	 * �?般情况下是这样的/storage/emulated/0/Android/data/包名/
	 * 
	 * @param context
	 * @return
	 */
	public static String getAppDir(Context context) {
		return (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ? (Environment.getExternalStorageDirectory().getPath() + "/Android/data/")
				: (context.getCacheDir().getPath()))
				+ context.getPackageName();
	}

	public static String getAppImageDir(Context context) {
		String file = getAppDir(context) + File.separator + "image" + File.separator;
		File imgFile = new File(file);
		if (!imgFile.exists()) {
			imgFile.mkdirs();
		}
		return file;
	}

	public static String getAppVoiceDir(Context context) {
		String file = getAppDir(context) + File.separator + "voice" + File.separator;
		File imgFile = new File(file);
		if (!imgFile.exists()) {
			imgFile.mkdirs();
		}
		return file;
	}

	public static Intent photo(Context context) {

		Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			String filePath = getAppDir(context) + "/image/";
			File files = new File(filePath);
			if (!files.exists()) {
				files.mkdirs();
			}

			File file = new File(filePath, String.valueOf(System.currentTimeMillis()) + ".jpg");
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			path = file.getPath();
			Uri imageUri = Uri.fromFile(file);
			openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		} else {
			ToastUtil.makeShortText(context, "请插入内存卡");
		}
		return openCameraIntent;
	}

	/**
	 * 根据手机的分辨率�? dp 的单�? 转成�? px(像素)
	 */
	public static int dip2px(Context context, float dpValue) {
		int px;
		final float scale = context.getResources().getDisplayMetrics().density;
		if (scale == 0) {
			px = (int) (dpValue * defaultDensity + 0.5f);
		} else {
			px = (int) (dpValue * scale + 0.5f);
		}
		return px;
	}

	/**
	 * 根据手机的分辨率�? px(像素) 的单�? 转成�? dp
	 */
	public static int px2dip(Context context, float pxValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		int dp;
		if (scale == 0) {
			dp = (int) (pxValue / defaultDensity + 0.5f);
		} else {
			dp = (int) (pxValue / scale + 0.5f);
		}
		return dp;
	}

	/**
	 * 获取设备ID
	 * 
	 * @param context
	 * @return
	 */
	public static String getIMEI(Context context) {
		TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
		if (!StringUtil.isEmpty(manager.getDeviceId())) {
			return manager.getDeviceId();
		} else {
			final String tmDevice, tmSerial, tmPhone, androidId;

			tmDevice = "" + manager.getDeviceId();

			tmSerial = "" + manager.getSimSerialNumber();

			androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);

			UUID deviceUuid = new UUID(androidId.hashCode(), ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());

			String uniqueId = deviceUuid.toString();

			LogUtil.e("android deviceId is null, uuid=" + uniqueId);
			return uniqueId;
		}
	}

	/**
	 * 获取应用AppKey
	 * 
	 * @return
	 */
	public static String getAppKey(Context context) {
		ApplicationInfo applicationInfo = null;
		String appKey = null;
		try {
			applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
			appKey = applicationInfo.metaData.getString("app_key");
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		LogUtil.i("app_key=" + appKey);
		return appKey;
	}

	public static String getAppSecret(Context context) {
		ApplicationInfo applicationInfo = null;
		String appSecret = null;
		try {
			applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
			appSecret = applicationInfo.metaData.getString("app_secret");
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		LogUtil.i("app_secret=" + appSecret);
		return appSecret;
	}

	public static boolean hasSDCard() {
		String state = Environment.getExternalStorageState();
		if (state.equals(Environment.MEDIA_MOUNTED)) {
			return true;
		}
		return false;
	}

	/**
	 * bitmap转成byte数组
	 * 
	 * @param avatar
	 * @return
	 */
	public static byte[] Bitmap2Bytes(Bitmap avatar) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		avatar.compress(Bitmap.CompressFormat.JPEG, 100, baos);
		return baos.toByteArray();

	}

	/**
	 * 此方法用于现场互动界�?,格式固定. e.g.day=18,mounth=九月.
	 * 
	 * @param day
	 * @param month
	 * @return
	 */
	public static boolean isToday(String day, String month) {
		Calendar c = Calendar.getInstance();
		int m = c.get(Calendar.MONTH);
		int d = c.get(Calendar.DAY_OF_MONTH);
		if (!StringUtil.isEmpty(day) && !StringUtil.isEmpty(month)) {
			if (month.equals(Num2Hanzi(m)) && String.valueOf(d).equals(day)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 转化月份.数字转汉�?
	 * 
	 * @param num
	 * @return
	 */
	public static String Num2Hanzi(int num) {
		StringBuffer sb = new StringBuffer();
		String[] strings = new String[] { "�?", "�?", "�?", "�?", "�?", "�?", "�?", "�?", "�?", "�?", "十一", "十二" };
		return sb.append(strings[num]).append("�?").toString();
	}

	/**
	 * 转化月份.汉字转数�?
	 * 
	 * @param hanzi
	 * @return
	 */
	public static int Hanzi2Num(String hanzi) {
		int num = 0;
		int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
		String[] strings = new String[] { "�?�?", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一�?", "十二�?" };
		for (int i = 0; i < strings.length; i++) {

			if (hanzi.equals(strings[i])) {
				num = numbers[i];
			}
		}
		return num;
	}

	/**
	 * 获取手机上的联系人电�?.
	 * 
	 * @return
	 */
	public static void getContacts(Context context, final IContactCallback callback) {
		final Context ctx = context;
		new Thread(new Runnable() {
			@Override
			public void run() {

				StringBuffer sb = new StringBuffer();
				Cursor cursor = ctx.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
				if (cursor != null) {
					while (cursor.moveToNext()) {

						String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
						String displayName = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
						int numberCount = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
						LogUtil.e("联系�?: " + displayName);
						if (numberCount > 0) {
							Cursor c = ctx.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
									ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + contactId, null, null);
							if (c != null) {
								while (c.moveToNext()) {
									String number = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
									if (number.contains(" ")) {
										number = number.replace(" ", "");
									}
									if (number.contains("-")) {
										number = number.replace("-", "");
									}
									// 截取�?11�?.针对前面�?+86前缀�?.
									if (number.length() > 11) {
										number = number.subSequence(number.length() - 11, number.length()).toString();
									}

									LogUtil.e("联系电话: " + number);
									sb.append(number);
									sb.append(",");
								}
								c.close();
								c = null;
							}
						}
					}
					cursor.close();
					cursor = null;
				}
				if (sb.toString().endsWith(",")) {
					sb.delete(sb.length() - 1, sb.length());
				}
				callback.callback(sb.toString());
			}

		}).start();
	}

	public interface IContactCallback {
		void callback(String string);
	}

	/**
	 * 
	 * 读取图片的旋转的角度
	 * 
	 * @param path
	 * 
	 *            图片绝对路径
	 * 
	 * @return 图片的旋转角�?
	 */

	private int getBitmapDegree(String path) {
		int degree = 0;
		try {
			// 从指定路径下读取图片，并获取其EXIF信息
			ExifInterface exifInterface = new ExifInterface(path);
			// 获取图片的旋转信�?
			int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
			case ExifInterface.ORIENTATION_ROTATE_90:
				degree = 90;
				break;
			case ExifInterface.ORIENTATION_ROTATE_180:
				degree = 180;
				break;
			case ExifInterface.ORIENTATION_ROTATE_270:
				degree = 270;
				break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;

	}

	/**
	 * 将图片按照某个角度进行旋�?
	 * 
	 * @param bm
	 *            �?要旋转的图片
	 * @param degree
	 *            旋转角度
	 * @return 旋转后的图片
	 */

	public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
		Bitmap returnBm = null;
		// 根据旋转角度，生成旋转矩�?
		Matrix matrix = new Matrix();
		matrix.postRotate(degree);
		try {
			// 将原始图片按照旋转矩阵进行旋转，并得到新的图�?
			returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

		} catch (OutOfMemoryError e) {
		}
		if (returnBm == null) {

			returnBm = bm;
		}
		if (bm != returnBm) {
			bm.recycle();
		}
		return returnBm;

	}
	
	// 6-12位数字大小
	public static boolean isEmail(String s) {
		String strPattern = "^[0-9a-zA-Z_]{6,12}$";
		Pattern p = Pattern.compile(strPattern);
		Matcher m = p.matcher(s);
		return m.matches();
	}
	
	// 判断字符串是否有空格
	public boolean hasKongge(String s) {
		int i = s.indexOf(' ');
		if (i != -1) {
			// 有空格
			return true;
		}
		// 无空格
		return false;
	}
	/**
	 * 二维码生成器
	 * @param number 订单号
	 * @param context 上下文
	 * @return
	 * @throws WriterException
	 * @throws Exception
	 */
	public static Bitmap show(String number,Context context) throws WriterException, Exception {
		final TelephonyManager tm = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
		String s = tm.getDeviceId() + (new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.CHINESE).format(new Date()));
		System.out.println(s);
		Bitmap qrCodeBitmap = EncodingHandler.createQRCode(number, 500);
		return qrCodeBitmap;
	}
}
